package com.wolfking.converter.web;

import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.wolfking.converter.exception.ParamVerifyException;
import com.wolfking.converter.util.JsonConverterUtil;
import com.wolfking.spi.SpiInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MissingServletRequestParameterException;

@Slf4j
@Component
@SpiInterface(code = "defaultResponseConverter")
public class DefaultResponseConverter implements WebResponseConverter {
    @Override
    public Object convertOne(JsonObject jsonObject) {
        return JsonConverterUtil.toMap(jsonObject);
    }

    @Override
    public Object convertList(JsonArray jsonArray) {
        return JsonConverterUtil.toListMap(jsonArray);
    }

    @Override
    public Object convertException(Exception e) throws Exception {
        log.error("", e);
        if (e instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException parameterException = (MissingServletRequestParameterException) e;
            return ImmutableMap.of("code", 500, "message", String.format("%s参数缺失", parameterException.getParameterName()));
        } else if (e instanceof ParamVerifyException) {
            ParamVerifyException parameterException = (ParamVerifyException) e;
            return ImmutableMap.of("code", 500, "message", e.getMessage());
        }
        throw e;
    }
}
